import { defineStore } from "pinia";
import { useUserStore } from "./useUserStore";
// import { useBindingStore } from "./useBindingStore";

import { get, post } from "../../utils/request";
import { ref, computed } from "vue";

export const useRecordStore = defineStore("record", () => {
  const userStore = useUserStore();
  //   const bindingStore = useBindingStore();

  const curUserId = ref(1);

  // 初始化用药列表
  const medicationList = ref([]);
  



  // 初始化病历记录列表
  const medicalRecordList = ref([]);
  


  const selectedMedicalRecord = ref(null);
  const selectedMedication = ref(null);

  function setSelectedMedicalRecord(record) {
    selectedMedicalRecord.value = record;
  }

  function setSelectedMedication(record) {
    selectedMedication.value = record;
  }

  const getSelectedMedicalRecord = computed(() => selectedMedicalRecord.value);
  const getSelectedMedication = computed(() => selectedMedication.value);
  
  // 添加安全访问的计算属性
  const getMedicationList = computed(() => {
    return medicationList.value || [];
  });
  
  const getMedicalRecordList = computed(() => {
    return medicalRecordList.value || [];
  });

  const addMedication = async (data) => {
    const Data = {
      userId: curUserId.value,
      ...data,
    };

    try {
      const res = await post("/record/addMedication", Data, "api/v1", {
        method: "POST",
      });

      if (res && res?.code === 200) {
        medicationList.value.push(data);
        return res.data;
      } else {
        console.log(res?.msg);
        throw new Error(res?.msg || "添加失败");
      }
    } catch (error) {
      console.log(error);
      throw new Error(error);
    }
  };

  const addMedicalRecord = async (data) => {

    console.log('!!!!!!!!!!!!--',curUserId.value)

    const Data = {
      userId: curUserId.value,
      ...data,
    };

    try {
      const res = await post("/record/addMedicalRecord", Data, "api/v1", {
        method: "POST",
      });

      if (res && res?.code === 200) {
        medicalRecordList.value.push(data);
        return res.data;
      } else {
        console.log(res?.msg);
        throw new Error(res?.msg || "添加失败");
      }
    } catch (error) {
      console.log(error);
      throw new Error(error);
    }
  };

  const fetchMedicationList = async (userId) => {

    if(!userId){
      userId = curUserId.value;
    }
    try {
      const res = await get(`/record/${userId}/medication`, "api/v1");

      if (res && res?.code === 200) {
        medicationList.value = res.data;
      } else if (res) {
        console.log(res?.msg);
        throw new Error("获取用药列表失败!", res?.msg);
      } else {
        throw new Error("Error fetching medication list");
      }

      return res;
    } catch (error) {
      console.log(error);
      throw error;
    }
  };

  const fetchMedicalRecordList = async (userId) => {
    if(!userId){
      userId = curUserId.value;
    }
    try {
      const res = await get(`/record/${userId}/medicalRecord`, "api/v1");
      if (res && res.code === 200) {
        medicalRecordList.value = res.data;
      } else if (res) {
        console.log(res?.msg);
        throw new Error("获取用药列表失败!", res?.msg);
      } else {
        throw new Error("Error fetching medication list");
      }
    } catch (error) {
      console.log(error);
      throw error;
    }
  };

  const delMedication = async (id) => {
    try {
      const res = await post(
        "/record/delMedication",
        { medicationId: id, userId: curUserId.value },
        "api/v1",
        { method: "POST" }
      );

      if (res?.code === 200) {
        medicationList.value = medicationList.value.filter((m) => m.id !== id);
      } else if (res) {
        console.log(res?.msg);
        throw new Error("删除用药失败!", res?.msg);
      } else {
        throw new Error("Error deleting medication");
      }
    } catch (error) {
      console.log(error);
      throw error;
    }
  };

  const delMedicalRecord = async (id) => {
    // console.log( { userId: curUserId.value, recordId: id })
    try {
      const res = await post(
        `/record/delMedicalRecord`,
        { userId: curUserId.value, recordId: id },
        "api/v1",
        { method: "POST" }
      );

      if (res?.code === 200) {
        medicalRecordList.value = medicalRecordList.value.filter(
          (m) => m.id !== id
        );
      } else if (res) {
        console.log(res?.msg);
        throw new Error("删除病历失败!", res?.msg);
      } else {
        throw new Error("Error deleting medicalRecord");
      }
    } catch (error) {
      console.log(error);
      throw error;
    }
  };

  const testApi = async () => {
    try {
      const medictionData = {
        medicationName: "Paracetamol",
        allergy: false,
        drugDiscription: "扑热息痛,对乙酰氨基酚这是一种非甾体的止疼退烧药....",
        dosage: "500 mg",
        frequency: "3 times a day",
        startDate: "2023-05-01",
        endDate: "2023-05-15",
      };

      const recordData = {
        hospital: "web Hospital",
        department: "web",
        diagnosis: "前后端对接异常",
        advice: "建议吃点全干工程师",
        time: "2026-01-28 01:18:53",
      };

      const id1 = await addMedication(medictionData);
      const id2 = await addMedicalRecord(recordData);
      await fetchMedicationList(1);
      await fetchMedicalRecordList(1);

      await delMedicalRecord(id2.id);
      await delMedication(id1.id);

      console.log("test api success");
    } catch (error) {
      console.log(error);
      return error;
    }
  };

  //   testApi();

  const allergyList = ref([]);

  const getAllergyList = computed(() => allergyList.value);

  const fetchAllergyList = async (userId) => {
    try {
      const res = await get(`/record/${userId}/medication?allergy=true`, "api/v1");

      if (res && res?.code === 200) {
        allergyList.value = res.data;
      } else if (res) {
        console.log(res?.msg);
        throw new Error("获取过敏药物列表失败!", res?.msg);
      } else {
        throw new Error("Error fetching allergy list");
      }

      return res;
    } catch (error) {
      console.log(error);
      throw error;
    }
  };

  const addAllergy = async (data) => {
    const Data = {
      userId: curUserId.value,
      ...data,
      allergy: true
    };

    console.log("addAllergy", Data);
    try {
      const res = await post("/record/addMedication", Data, "api/v1", {
        method: "POST",
      });
      console.log("addAllergy res", res);

      if (res && res?.code === 200) {
        allergyList.value.push(data);
        return res.data;
      } else {
        console.log(res?.msg);
        throw new Error(res?.msg || "添加失败");
      }
    } catch (error) {
      console.log(error);
      throw new Error(error);
    }
  };

  const delAllergy = async (id) => {
    try {
      const res = await post(
        "/record/delMedication",
        { medicationId: id, userId: curUserId.value },
        "api/v1",
        { method: "POST" }
      );

      if (res?.code === 200) {
        allergyList.value = allergyList.value.filter((m) => m.id !== id);
      } else if (res) {
        console.log(res?.msg);
        throw new Error("删除过敏药物失败!", res?.msg);
      } else {
        throw new Error("Error deleting allergy medication");
      }
    } catch (error) {
      console.log(error);
      throw error;
    }
  };

  const getCurUserId = computed(() => curUserId.value);

  const setCurUserId = (id) => {
    curUserId.value = id;
  };

  // 加载所有用户数据（药物、病历、过敏信息）
  const loadAllData = async (userId) => {
    try {
      const id = validateUserId(userId);
      setCurUserId(id);
      
      const isLoading = uni.showLoading({
        title: '加载患者数据...'
      });
      
      try {
        // 并行获取所有数据
        await Promise.all([
          fetchMedicationList(id),
          fetchMedicalRecordList(id),
          fetchAllergyList(id)
        ]);
        
        return {
          medicationList: medicationList.value,
          medicalRecordList: medicalRecordList.value,
          allergyList: allergyList.value
        };
      } finally {
        // 确保loading被关闭
        if (isLoading) {
          uni.hideLoading();
        }
      }
    } catch (error) {
      handleApiError(error, "加载患者数据失败");
      return {
        medicationList: [],
        medicalRecordList: [],
        allergyList: []
      };
    }
  };

  return {

    setCurUserId,
    getCurUserId,

    medicationList,
    medicalRecordList,
    getMedicationList,
    getMedicalRecordList,
    addMedication,
    addMedicalRecord,
    fetchMedicationList,
    fetchMedicalRecordList,
    delMedication,
    delMedicalRecord,
    
    selectedMedicalRecord,
    selectedMedication,
    getSelectedMedicalRecord,
    getSelectedMedication,
    setSelectedMedicalRecord,
    setSelectedMedication,
    allergyList,
    getAllergyList,
    fetchAllergyList,
    addAllergy,
    delAllergy,
    loadAllData,
  };
});
